﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using LoggingClient;

namespace ATMCommLib
{
    public class CommHost<T> where T : ICommHostHandler, new()
    {
        ILogger mlogger = null;

        public bool Start(ILogger logger, int port)
        {
            try
            {
                IPAddress ip = IPAddress.Any;
                TcpListener tcpListener = new TcpListener(ip, port);
                tcpListener.Start();

                mlogger.Info("==============================");
                mlogger.Info("CommHost Starting");
                mlogger.Info(string.Format("[Port]: {0}", port));
                mlogger.Info("Waiting for connection....");

                while (true)
                {
                    TcpClient tcpClient = tcpListener.AcceptTcpClient();
                    tcpClient.ReceiveTimeout = 30000;

                    mlogger.Info("Client connected");

                    NetworkStream ns = tcpClient.GetStream();

                    new T().Start(logger, ns);
                }
            }
            catch (Exception ex)
            {
                mlogger.Error(ex.ToString());
                return false;
            }
        }
    }
}
